/**
 * Created by Administrator on 2017/5/23.
 */
import  vueX      from  'vuex';
import  lockr       from 'lockr';
import  axIos      from 'axios';
import  {LOADING_START, LOADING_TIMEOUT, LOADING_REST} from './TipMessage';
import  {TOKEN_TIME_OUT} from './commConfig';
const AUTH_KEY = 'authKey';
const SESSION_ID = 'sessionId';
const TipsMessage = (loading_code) => {
  let information = '';
  switch (loading_code) {
    case 100:
      information = LOADING_START;
      break;
    case 101:
      information = LOADING_END;
      break;
    case 102:
      information = LOADING_TIMEOUT;
      break;
    default:
      information = LOADING_REST;
  }
  vueX.commit('tipInfo', information);
};
const stackToken = (response) => {
  let authKey = response.headers.authkey;
  let sessionId = response.headers.sessionid;
  lockr.set('authKey', JSON.stringify({data: authKey, time: TokenTimeOut()}));
  lockr.set('sessionId', JSON.stringify({data: sessionId, time: TokenTimeOut()}));
};
/**
 * 设置token 记得后台需要检测没有token那么需要抛出异常
 */
const setToken = () => {
  checkTokenSurvive();
};
/**
 * @returns {*}
 * @constructor   返回当前的token的超时时间
 */
const TokenTimeOut = () => {
  return (new Date().getTime()) + TOKEN_TIME_OUT;
};
/**
 *
 * @returns {boolean} 检查token是否过期过期需要重新登录
 */
const checkTokenSurvive = () => {
  let AuthKeyData = lockr.get(AUTH_KEY), sessionIdData = lockr.get(SESSION_ID), JudgeTime = false;
  if (AuthKeyData && sessionIdData) {
    AuthKeyData = JSON.parse(AuthKeyData), sessionIdData = JSON.parse(sessionIdData);
    JudgeTime = timeOutCheck(AuthKeyData.time);
    store.state.tokenAuth = JudgeTime;
  }
  if (true === JudgeTime) {
    axIos.defaults.headers.authKey = AuthKeyData.data;
    axIos.defaults.headers.sessionid = sessionIdData.data;
    return JudgeTime;
  }
  lockr.rm(AUTH_KEY);
  lockr.rm(SESSION_ID);
  axIos.defaults.headers.authKey = '';
  axIos.defaults.headers.sessionid = '';
};
/**
 * @param expire       type int
 * @returns {boolean}  是否超时
 */
const checkLoginTimeout = (expire) => {
  if (!expire) {
    return false;
  }
  let JudgeTime = timeOutCheck(expire);
  return JudgeTime;
};
/**
 * @param oldTime   type int     设置的过期时间
 * @returns {boolean}             是否过期
 */
const timeOutCheck = (oldTime) => {
  return (new Date().getTime())-oldTime<=0?true:false;
};

export  {TipsMessage, setToken, stackToken, checkLoginTimeout}
